Python知识精解:str replace()方法 您所在的位置:网站首页 python str 删除字符 Python知识精解:str replace()方法

Python知识精解:str replace()方法

2023-03-11 04:59| 来源: 网络整理| 查看: 265

描述

Python 字符串 replace()方法是字符串替换方法,它可将字符串中的部分子串替换成新的部分,并返回新字符串。

语法和参数str.replace(old_str, new_str, count)返回值

string,返回替换后的新字符串。若old_str在字符串中不存在,则返回原字符串。

实例

1. 省略count时

当count参数省略时,在字符串中匹配到的全部old_str将会被替换成new_str:

if __name__ == '__main__': demo = "Python: python language is fun. I love python." print("before replace():\t", demo, id(demo)) r = demo.replace("python", "Java") print("after replace():\t", r, id(r))

运行结果:

before replace(): Python: python language is fun. I love python. 4509860464 after replace(): Python: Java language is fun. I love Java. 4509860560

2. count值存在

如果没有省略最后的参数count,replace()方法仅将old_str替换为new_str的次数与count值相等。即replace()替换字符串的次数取决于count值的大小。

下面的例子中,我们只替换一次:

>>> demo = "洛阳是河南省的著名城市,洛阳也是中国古代的著名都城。" >>> result = demo.replace("洛阳", "开封", 1) >>> result '开封是河南省的著名城市,开封也是中国古代的著名都城。' >>> id(demo) 4366833712 >>> id(result) 4366833840

注意事项

1. old_str与new_str相等时

当要新替换的字符串与旧字符串相等时,replace()方法不会报错。此时如果new_str将old_str全部替换完,replace()方法返回原字符串。

>>> demo = "banana, apple, orange" >>> result = demo.replace("apple", "apple") >>> result 'banana, apple, orange' >>> id(demo) 4367589288 >>> id(result) 4367589288

2. count值大于old_str出现的次数

当count值大于old_str出现的次数时,replace()方法不会报错,此时count参数出现没有任何意义:

>>> demo = "go.micro.compute" >>> result = demo.replace("go", "python", 100) >>> result 'python.micro.compute'

3. old_str在字符串中不存在

当old_str在原字符串中不存在时,使用replace()方法不会报错,并返回原字符串:

if __name__ == '__main__': place = "caf\u00e9" result = place.replace("e", "~") print("place", place) print("result", result) print("place id", id(place)) print("result id", id(result))

运行结果:

place café result café place id 4553216048 result id 4553216048

4. count值为0

count值为0,replace()不会做任何操作,返回原字符串。

if __name__ == '__main__': action = "I like having coffee at starbucks" result = action.replace("coffee", "water", 0) print("action", action) print("result", result) print("action id:", id(action)) print("result id:", id(result))

运行结果:

action I like having coffee at starbucks result I like having coffee at starbucks action id: 4513124264 result id: 4513124264

5. count值为负

当count值为负,replace()方法将全部old_str替换为new_str。这种场景下count参数作用失效:

if __name__ == '__main__': action = "a a a b c" result = action.replace("a", "d", -1) print("action", action) print("result", result) print("action id:", id(action)) print("result id:", id(result))

运行结果:

action a a a b c result d d d b c action id: 4318863024 result id: 4319003120

觉得有用的同学可以点下赞同呀~

关注我,获得更多技术知识~



【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有